Golang : Match strings by wildcard patterns with filepath.Match() function
Problem:
You want to match strings using the same wildcard patterns commonly used in Linux/Unix shells such as *.go
or *data[0-9]*
. How to do that?
Solution:
package main
import (
"fmt"
"path/filepath"
)
func main() {
filename := "start.txt"
pattern := "*art*"
matched, err := filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
//---------------------------------
pattern = "*fart*"
matched, err = filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
//---------------------------------
filename = "data123.csv"
pattern = "data[0-9]*"
matched, err = filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
}
Output :
true
false
true
NOTES: This example is for matching strings. For filenames in the current or specific directory. See this tutorial https://socketloop.com/tutorials/golang-use-wildcard-patterns-with-filepath-glob-example
It should work as well if you replace filepath.Match()
with path.Match()
Reference:
See also : Golang : Use wildcard patterns with filepath.Glob() example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.7k Javascript : Access JSON data example
+9.7k Javascript : Read/parse JSON data from HTTP response
+40.2k Golang : UDP client server read write example
+7.8k Gogland : Where to put source code files in package directory for rookie
+13.8k Golang : Tutorial on loading GOB and PEM files
+15.3k Golang : Get timezone offset from date or timestamp
+25.8k Golang : missing Mercurial command
+7.1k Golang : constant 20013 overflows byte error message
+6.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+14.6k How to automatically restart your crashed Golang server
+16k Golang : Get current time from the Internet time server(ntp) example
+6.6k Unix/Linux : How to get own IP address ?